<template>
    <div>
     <el-form
    ref="roleFormRef"
    style="max-width: 600px"
    :model="updateRole"
    :rules="rules"
    label-width="100px"
    label-position="right"
    width = "400px"
    >
    <el-form-item label="角色名称" prop="name">
      <el-input v-model="updateRole.name"  aria-placeholder="请输入角色名称" />
    </el-form-item>

    <el-tree
    style="max-width: 600px"
    :data="authList"
    show-checkbox
    node-key="index"
    :default-expanded-all="true"
    :default-checked-keys="checkedKeys"
    @check-change="handleCheckChange"/>
  </el-form>
    </div>
</template>
<script setup lang="ts">
import type { roleInfoData } from '@/api/role/type';

import type { FormRules } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';
    //引入菜单项数组
    import menuList from '@/config/menuConfig';
    //接收父组件传递过来的要编辑的角色对象
    const props = defineProps(["role"]);
    // let updateRole = reactive<roleInfoData>({
    //     name:""
    // })
    
    let updateRole = ref<roleInfoData>({
        name:""
    })
    //表达校验规则
    const rules = reactive<FormRules>({
        name:[{required:true,message:"请输入角色名称",trigger:"blur"}]
    });
    //树形控件默认的选中数组
    let checkedKeys = reactive<any>([]);
    //树形空间数据数组
    const authList = ref([])


    //处理属性控件元素对象
    const getAuthNodes = (menuList:any)=>{
        return menuList.map((item:any)=>{
            if(!item.children){
                return{
                    index:item.index,
                    label:item.title
                }
            }else{
                return{
                    index:item.index,
                    label:item.title,
                    children:getAuthNodes(item.children)
                }
            }
        })
    }
    
    interface Tree{
        index:string
    }
    //树形控件选择回调
    const handleCheckChange = (
        data:Tree,
        checked:boolean,
        indeterminate:boolean
    )=>{
        if(checked){
            //选中的是/students不能加入到队列中，/students就是二级菜单的头，没有实际意义
            //已存在的也不能添加
            if(data.index != "/students" && checkedKeys.indexOf(data.index) == -1){
                checkedKeys.push(data.index)
                console.log(checkedKeys);
            }
        }else{
            if(checkedKeys.indexOf(data.index) != -1){
                checkedKeys.splice(checkedKeys.indexOf(data.index),1);
                console.log(checkedKeys);
            }
        }
        
    };
    //将处理后的权限赋值给updataRole
    const getMenus = ()=>{
        updateRole.value.menus = checkedKeys;
        return updateRole;
    }
    //需要暴露给父组件
    defineExpose({
        getMenus
    })
    onMounted(()=>{
        updateRole.value = {...props.role}
        // Object.assign(updateRole, props.role);
        authList.value = getAuthNodes(menuList)
        checkedKeys = [...props.role.menus]
    });
    

</script>